package com.qf.fmall2202.interceptor;

import com.qf.fmall2202.exception.QFException;
import com.qf.fmall2202.utils.CommonContants;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 检查请求中的token是否合法
 */
@Component
public class TokenInterCeptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //放行浏览器的跨域OPTIONS 请求
        String method = request.getMethod();
        if (method.equals("OPTIONS")){
            return true;
        }

        String token = request.getHeader("token");

        //校验token是否合法
        //解析
        JwtParser parser = Jwts.parser();
        parser.setSigningKey(CommonContants.JWT_SECRET_KEY);

        try {
            Jwt jwt = parser.parse(token);
        } catch (IllegalArgumentException e) {
            throw  new QFException("token有问题吧小子重新登录");
        }
        //把请求放行
        return true;
    }
}
